<?php

/**
 * 发票接口
 */
class Action
{

    private $per_page = 50;

    private $token = '';
    private $user_id = 0;
    private $user_info = array();
    private $api_stat_id = 0;

    public function __construct() {
        $this->token = an_request('token');

        if ($this->token) {
            $user_info = user_helper::get_user_info_by_token($this->token);
            if ($user_info && $user_info['status'] == 1) {
                $this->user_id = $user_info['id'];
                $this->user_info = $user_info;
            }
        }
    }

    /**
     * 查询用户的可开票额度
     * @author xiaolin
     * @date   2016-09-01
     * @return json
     */
    public function invoice_amount() {
        $object_type = an_request('object_type', 1);

        //加密参数
        $sign_param = array(
            //'object_type' => $object_type //暂时不加密
        );
        // 验证接口
        $this->api_stat_id = api_helper::check_sign($sign_param, 1);

        $amount = invoice_helper::get_user_invoice_amount($this->user_id, $object_type);
        api_helper::return_data(0, 'success', array('amount' => $amount), $this->api_stat_id);
    }

    /**
     * 已开发票列表
     * @author xiaolin
     * @date   2016-08-30
     * @return json
     */
    public function invoice_list() {
        $page_no = an_request('page_no', 1);

        //加密参数
        $sign_param = array(
            'page_no' => $page_no
        );

        // 验证接口
        $this->api_stat_id = api_helper::check_sign($sign_param, 1);

        //查询条件
        $filter['is_enable'] = 1;
        $filter['user_id'] = $this->user_id;
        $filter['status'] = array(0, 1, 3, 4); //待审核,待开票,待邮寄,完成
        $count = _model('invoice')->getTotal(enable_filter($filter));
        if (!$count) {
            api_helper::return_data(1, '暂无数据');
        }

        //分页配置
        $pager = new Pager($this->per_page);
        $pager->generate($count);
        $page_arr['page_no'] = $page_no;
        $page_arr['pages'] = $pager->getPages();
        
        //查询历史订单
        $invoice_list = _model('invoice')->getList($filter, 'ORDER BY `id` DESC ' . $pager->getLimit($page_no));
        $invoice_list = format_money($invoice_list, 'price_sum'); //格式化金钱

        //处理发票状态
        $invoice_list = $this->hanle_invoice_status($invoice_list);

        api_helper::return_data(0, 'success', array('invoice_list' => $invoice_list, 'pages' => $page_arr), $this->api_stat_id);
    }

    /**
     * 发票详情
     * @author xiaolin
     * @date   2016-08-30
     * @return json
     */
    public function invoice_detail() {
        $invoice_id = an_request('invoice_id');

        //参数验证
        $this->id_validation($invoice_id, '发票ID不能为空');

        //加密参数
        $sign_param = array(
            'invoice_id' => $invoice_id
        );

        // 验证接口
        $this->api_stat_id = api_helper::check_sign($sign_param, 1);

        $invoice = _uri('invoice', array('id' => $invoice_id, 'status' => array(0, 1, 3, 4)));
        if (!$invoice) {
            api_helper::return_data(1, '此发票不存在或者已驳回或者已删除');
        }

        //其他数据获取
        $invoice_courier  = _model('invoice_courier')->field('mailed_time')->read(array('invoice_id' => $invoice_id));
        $invoice['mailed_time'] = $invoice_courier ? date('Y-m-d', strtotime($invoice_courier['mailed_time'])): ''; //获取邮寄时间
        $invoice['price_sum']= format_money($invoice['price_sum']); //格式化金钱
        $invoice['order_total'] = invoice_helper::get_order_total_by_invoiceId($invoice_id); //统计order个数
        $invoice['status'] = $this->hanle_invoice_status($invoice['status']); //处理发票状态

        api_helper::return_data(0, 'success', array('invoice' => $invoice), $this->api_stat_id);
    }

    /**
     * 根据发票的ID查询该发票下的所有订单的详情
     * @author xiaolin
     * @date   2016-08-30
     * @return json
     */
    public function invoice_order_list() {
        $invoice_id = an_request('invoice_id');

        //参数验证
        $this->id_validation($invoice_id, '发票ID不能为空');

        //加密参数
        $sign_param = array(
            'invoice_id' => $invoice_id
        );

        // 验证接口
        $this->api_stat_id = api_helper::check_sign($sign_param, 1);

        //获取该发票对应的订单的ID
        $order_ids = _model('invoice_relation')->getFields('order_id', array(
            'invoice_id' => $invoice_id
        ));
        if (!$order_ids) {
            api_helper::return_data(1, '该发票下没有对应的订单');
        }

        //获取订单及所在店铺的信息
        $filter['id'] = $order_ids;
        $order_list = _model('order')->field('id', 'add_time', 'price', 'store_id')->getList($filter);
        if (count($order_list) == 0) {
            api_helper::return_data(1, '暂无数据');
        }
        //转化订单号
        foreach ($order_list as $key => $value) {
            $order_list[$key]['title'] = store_helper::get_store_title($value['store_id'], 1);
            $order_list[$key]['order_no'] = order_helper::order_id_encode($value['id']);
            $order_list[$key]['price'] = format_money($value['price']);
            $order_list[$key]['order_time'] = $value['add_time']; // add_time as order_time
            unset($order_list[$key]['store_id']);
            unset($order_list[$key]['add_time']);
        }

        api_helper::return_data(0, 'success', array('order_list' => $order_list), $this->api_stat_id);
    }

    /**
     * 给订单开具发票
     * @author xiaolin
     * @date   2016-08-25
     * @return json
     */
    public function make_invoice() {
        $order_ids = an_request('order_ids', '', 'request', 0);
        $object_type = an_request('object_type', 1); //当前只有合伙人给掌柜开票,此参数客户端不需要传,也不加密
        $company_name = an_request('company_name', '');
        $price_sum= an_request('price_sum', '0.00');
        $type = an_request('type', '0');
        $recipient_name = an_request('recipient_name', '');
        $recipient_phone = an_request('recipient_phone', '');
        $recipient_area = an_request('recipient_area', '');
        $recipient_address = an_request('recipient_address', '');
        $taxpayer_number = an_request('taxpayer_number', '');
        $billing_address = an_request('billing_address', '');
        $billing_phone = an_request('billing_phone', '');
        $bank_name = an_request('bank_name', '');
        $bank_number = an_request('bank_number', '');
        $remark = an_request('remark', '');

        //加密参数
        $sign_param = array(
            'order_ids' => $order_ids,
            'company_name' => $company_name,
            'price_sum' => $price_sum,
            'type' => $type,
            'recipient_name' => $recipient_name,
            'recipient_phone' => $recipient_phone,
            'recipient_area' => $recipient_area,
            'recipient_address' => $recipient_address,
            'taxpayer_number' => $taxpayer_number,
            'billing_address' => $billing_address,
            'billing_phone' => $billing_phone,
            'bank_name' => $bank_name,
            'bank_number' => $bank_number
        );

        //验证是否可开票
        $is_invoice = invoice_helper::is_enable_make_invoice($this->user_id);
        if (!$is_invoice) {
            api_helper::return_data(1, '您还没有开票权限,请联系客服申请开通');
        }

        //数据格式及必填校验
        $this->make_invoice_validation($sign_param);

        // 验证接口
        $this->api_stat_id = api_helper::check_sign($sign_param, 1);

        $price_sum = format_money($price_sum); //格式化金钱
        //验证开票金额是否大于可开票额度
        if ($price_sum > invoice_helper::get_user_invoice_amount($this->user_id, $object_type)) {
            api_helper::return_data(1, '您所开具的发票金额大于您的可开票额度,请减少开票订单或者进货');
        }

        $order_ids = json_decode($order_ids, true);
        //验证是否有已开票的订单
        $count_sql = 'select count(id) as num from `order` where id in (' . implode(',', $order_ids). ') and make_invoice_status = 1';
        $current_order_count = _model('order')->getAll($count_sql)[0]['num'];
        if ($current_order_count) {
            api_helper::return_data(1, '您所选择的订单中有已开票的订单，请核对后再开票');
        }

        //事务开始
        ts_helper::begin();
        try {
            //修改订单开票状态
            ts_helper::_model('order')->update(array('id' => $order_ids), array(
                'make_invoice_status' => 1,
                'make_invoice_time' => date('Y-m-d H:i:s')
            ));

            //合伙人可开发票额度减少
            $change_res = invoice_helper::change_user_invoice_amount($this->user_id, $price_sum, $object_type, 2, 1);

            $invoice_create_data = array(
                'user_id' => $this->user_id,
                'object_type' => $object_type,
                'company_name' => $company_name,
                'price_sum' => $price_sum,
                'type' => $type,
                'recipient_name' => $recipient_name,
                'recipient_phone' => $recipient_phone,
                'recipient_area' => $recipient_area,
                'recipient_address' => $recipient_address,
                'taxpayer_number' => $taxpayer_number,
                'billing_address' => $billing_address,
                'billing_phone' => $billing_phone,
                'bank_name' => $bank_name,
                'bank_number' => $bank_number,
                'remark' => $remark,
                'add_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s')
            );

            //如果额度减少成功,则增加改变记录
            if ($change_res['flag'] === 0 && !empty($change_res['data'])) {
                $invoice_create_data['change_amount_log'] = $change_res['data'];
            }

            //添加一条发票记录
            $invoice_id = ts_helper::_model('invoice')->create($invoice_create_data);

            //循环添加发票和订单关联
            foreach ($order_ids as $id) {
                ts_helper::_model('invoice_relation')->create(array(
                    'invoice_id' => $invoice_id,
                    'order_id' => $id,
                    'add_time' => date('Y-m-d H:i:s'),
                    'update_time' => date('Y-m-d H:i:s')
                ));
            }

            //插入模板表
            $template_data = array(
                'user_id' => $this->user_id,
                'company_name' => $company_name,
                'type' => $type,
                'recipient_name' => $recipient_name,
                'recipient_phone' => $recipient_phone,
                'recipient_area' => $recipient_area,
                'recipient_address' => $recipient_address,
                'taxpayer_number' => $taxpayer_number,
                'billing_address' => $billing_address,
                'billing_phone' => $billing_phone,
                'bank_name' => $bank_name,
                'bank_number' => $bank_number
            );

            $template_str = join('', $template_data);
            $template_salt= md5($template_str);

            $invoice_template = _uri('invoice_template', array('salt' => $template_salt));
            //如果不存在相同记录时才添加
            if (!$invoice_template) {
                $template_data['salt'] = $template_salt;
                $template_data['add_time'] = datetime();
                $template_data['update_time'] = datetime();

                ts_helper::_model('invoice_template')->create($template_data);
            }

            ts_helper::commit();
            api_helper::return_data(0, 'success', array(), $this->api_stat_id);
        } catch (Exception $e) {
            ts_helper::trace_log($e);
            ts_helper::rollback();
            api_helper::return_data(1, '开票失败');
        }
    }

    /**
     * 获取发票模版
     * @author xiaolin
     * @date   2016-09-14
     * @return json
     */
    public function invoice_template_list() {
        $page_no = an_request('page_no', 1);

        //加密参数
        $sign_param = array(
            'page_no' => $page_no
        );

        // 验证接口
        $this->api_stat_id = api_helper::check_sign($sign_param, 1);


        $filter['user_id'] = $this->user_id;
        $filter['status'] = 1;
        $count = _model('invoice_template')->getTotal($filter);
        if (!$count) {
            api_helper::return_data(1, '暂无数据');
        }

        //分页配置
        $pager = new Pager($this->per_page);
        $pager->generate($count);
        $page_arr['page_no'] = $page_no;
        $page_arr['pages'] = $pager->getPages();

        $invoice_template_list = _model('invoice_template')->getList($filter, 'order by id desc ' . $pager->getLimit($page_no));

        api_helper::return_data(0, 'success', array(
            'list' => $invoice_template_list,
            'pages' => $page_arr
        ), $this->api_stat_id);
    }

    /**
     * 删除发票模版
     * @author xiaolin
     * @date   2016-09-14
     * @return json
     */
    public function delete_invoice_template() {
        $template_ids = an_request('template_ids', '', 'request', 0);

        //加密参数
        $sign_param = array(
            'template_ids' => $template_ids
        );

        //参数校验
        $this->id_validation($template_ids, '发票模版ID不能为空');
        $template_ids = json_decode($template_ids, true);
        if (empty($template_ids)) {
            api_helper::return_data(1, '至少选择一个模版');
        }

        // 验证接口
        $this->api_stat_id = api_helper::check_sign($sign_param, 1);


        $res = _model('invoice_template')->update(array('id' => $template_ids), array(
            'status' => 0,
            'update_time' => datetime()
        ));

        if (!$res) {
            api_helper::return_data(1, '删除失败');
        }
        api_helper::return_data(0, 'success', array(), $this->api_stat_id);
    }

    /**
     * 发票列表,详情状态处理
     * @param int|array|object $data
     * @return int|array|object
     */
    private function hanle_invoice_status($data) {
        //status在0,1为待开票,传给客户端为1
        //status在3,4为已开票,传给客户端为2
        if (is_array($data)) {
            foreach ($data as $key => $value) {
                if (in_array($value['status'], array(0, 1))) {
                    $data[$key]['status'] = 1;
                } elseif(in_array($value['status'], array(3, 4))) {
                    $data[$key]['status'] = 2;
                }
            }
        } elseif (is_object($data)) {
            foreach ($data as $key => $value) {
                if (in_array($value->status, array(0, 1))) {
                    $data->$key->status = 1;
                } elseif(in_array($value->status, array(3, 4))) {
                    $data->$key->status = 2;
                }
            }
        } else {
            if (in_array($data, array(0, 1))) {
                $data = 1;
            } elseif(in_array($data, array(3, 4))) {
                $data = 2;
            }
        }

        return $data;
    }

    /**
     * 验证id是否为空
     * @author xiaolin
     * @date   2016-08-31
     * @param int $id 要验证的id
     * @param string $info 提示消息
     * @return json
     */
    private function id_validation($id, $info = 'ID不能为空') {
        if (!$id) {
            api_helper::return_data(1, $info);
        }
    }

    /**
     * 开具发票数据格式及必填校验
     * @author xiaolin
     * @date   2016-08-31
     * @param $params 要验证的数据
     * @return json
     */
    private function make_invoice_validation($params) {
        if (!$params['order_ids']) {
            api_helper::return_data(1, '请选择您要开具发票的订单');
        }
        $order_ids = json_decode($params['order_ids'], true);
        if (empty($order_ids)) {
            api_helper::return_data(1, '至少选择一个订单');
        }
        if (!is_array($order_ids)) {
            api_helper::return_data(1, '订单ID格式有误');
        }
        if (!$params['company_name']) {
            api_helper::return_data(1, '公司抬头必填');
        }
        if (!is_numeric($params['price_sum'])) {
            api_helper::return_data(1, '开票金额类型不正确');
        }
        if ($params['type'] == 1) {
            if (!$params['taxpayer_number']) {
                api_helper::return_data(1, '纳税人识别号必填');
            }
            /*纳税人识别号有字母
            if (!is_numeric($params['taxpayer_number'])) {
                api_helper::return_data(1, '纳税人识别号类型不正确');
            }*/
            if (!$params['billing_address']) {
                api_helper::return_data(1, '开票地址必填');
            }
            if (!$params['billing_phone']) {
                api_helper::return_data(1, '开票电话必填');
            }
            if (!$params['bank_name']) {
                api_helper::return_data(1, '开户银行必填');
            }
            if (!$params['bank_number']) {
                api_helper::return_data(1, '银行账号必填');
            }
        }
        if (!$params['recipient_name']) {
            api_helper::return_data(1, '收件人必填');
        }
        if (!$params['recipient_phone']) {
            api_helper::return_data(1, '联系电话必填');
        }
        if (!$params['recipient_area']) {
            api_helper::return_data(1, '所在地区必填');
        }
        if (!$params['recipient_address']) {
            api_helper::return_data(1, '邮寄地址必填');
        }
    }
}